<script setup>
import {inject, onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {doGet, doPost} from "../http/httpRequest.js";
import {showMessage} from "../util/utils.js";

//定义router对象
let router = useRouter(); //调对象的方法
let route = useRoute(); //点对象的属性

let customerDetail = ref({
  intentionProductDO : {},
  createByDO : {},
  editByDO : {}
})

let customerRemarkRules = ref({
  noteContent : [
    { required: true, message: '跟踪内容不能为空', trigger: 'blur' },
    { min: 5, max: 255, message: '跟踪内容长度为5-255位', trigger: 'blur' }
  ],
  noteWay : [
    { required: true, message: '请选择跟踪方式', trigger: ['blur', 'change'] }
  ]
})
let customerRemark = ref({})

onMounted(() => {
  loadCustomer()
  loadCustomerRemarkByPage(1)
})

const loadCustomer = () => {
  let customerId = route.params.customerId;
  doGet('/api/customer/' + customerId, {}).then(resp => {
    if (resp.data.code === 200) {
      customerDetail.value = resp.data.data;
      if (!resp.data.data.intentionProductDO) {
        //避免后端没有查询到createByDO创建人，前端读name字段的时候报null的错误
        customerDetail.value.intentionProductDO = {}
      }
      if (!resp.data.data.createByDO) {
        //避免后端没有查询到createByDO创建人，前端读name字段的时候报null的错误
        customerDetail.value.createByDO = {}
      }
      if (!resp.data.data.editByDO) {
        //避免后端没有查询到editByDO编辑人，前端读name字段的时候报null的错误
        customerDetail.value.editByDO = {}
      }
    } else {
      //提示一下
      showMessage('数据加载失败', 'error');
    }
  })
}

//联系方式的对象数组，初始值是空
let noteWayOptions = ref([{}])
let stageOptions = ref([{}])

//根据字典类型code加载字典值数据
const loadDicValue = (typeCode) => {
  doGet('/api/dic/'+ typeCode, {}).then(resp => {
    if (resp.data.code === 200) {
      if (typeCode === 'noteWay') {
        noteWayOptions.value = resp.data.data.dicValueDOList;
      } else if (typeCode === 'stage') {
        stageOptions.value = resp.data.data.dicValueDOList;
      }
    }
  })
}

//注入刷新函数
let flushPage = inject('flush');

let clueRemarkRuleFormRef = ref()
//客户提交跟踪记录
const customerRemarkSubmit = (formRef) => {
  if (!formRef) { //如果formEl不存在，也就是你没有给login()函数传userFormRef参数，那么就return，不做验证了
    return
  }
  formRef.validate((valid) => {
    if (valid) { //valid是true表示验证通过，否则没通过
      doPost('/api/customer/remark', {
        customerId : customerDetail.value.id, //客户id
        noteWay : customerRemark.value.noteWay, //跟踪方式
        noteContent : customerRemark.value.noteContent //跟踪内容
      }).then(resp => {
        if (resp.data.code === 200) {
          showMessage('跟踪记录提交成功', 'success');
          //页面局部刷新
          flushPage();
        } else {
          showMessage('跟踪记录提交失败，原因：' + resp.data.msg, 'error');
        }
      })
    }
  })
}

const goBack = () => {
  router.back();
}

//客户跟踪记录的list，初始值是空
let customerRemarkList = ref([{
  noteWayDO : {},
  createByDO : {},
  editByDO : {}
}])
//分页时总共有多少条数据
let total = ref(0)
//分页时每页显示多少条数据
let pageSize = ref(0)

//分页查询客户的历史跟踪记录
const loadCustomerRemarkByPage = (current) => {
  let customerId = route.params.customerId
  doGet('/api/customer/remarks', {
    current : current,
    customerId : customerId
  }).then(resp => {
    if (resp.data.code === 200) {
      customerRemarkList.value = resp.data.data.list;
      total.value = resp.data.data.total;
      pageSize.value = resp.data.data.pageSize;
    } else {
      showMessage('数据加载失败', 'error');
    }
  })
}

//分页函数
const toPage = (value) => {
  loadCustomerRemarkByPage(value);
}

let createTranVisible = ref(false)
let tranQuery = ref({})
let tranRules = ref({
  money : [
    { required: true, message: '请输入交易金额', trigger: 'blur' },
    { pattern: /^-?\d+(\.\d{1,2})?$/, message: '交易金额必须是整数或者两位小数', trigger: 'blur'}
  ],
  expectedDate : [
    { required: true, message: '请选择预计成交时间', trigger: 'blur' },
  ],
  stage : [
    { required: true, message: '请选择交易阶段', trigger: 'blur' },
  ],
  description : [
    { min: 5, max: 255, message: '交易描述长度为5-255个字符', trigger: 'blur' }
  ],
  nextContactTime : [
    { required: true, message: '请选择下次跟踪时间', trigger: 'blur' },
  ]
})

//创建交易函数
const createTran = () => {
  createTranVisible.value = true;
}

let tranFormRef = ref()

//创建交易（提交）
const createTranSubmit = (formEl) => {
  if (!formEl) { //如果formEl不存在，也就是你没有给login()函数传userFormRef参数，那么就return，不做验证了
    return
  }
  formEl.validate((valid) => {
    if (valid) { //valid是true表示验证通过，否则没通过
      let formData = new FormData();
      formData.append("customerId", customerDetail.value.id) //客户ID
      for (let field in tranQuery.value) {
        if (tranQuery.value[field]) { //该字段有值，我们才放入formData中
          formData.append(field, tranQuery.value[field]);
        }
      }
      doPost('/api/tran', formData).then(resp => {
        if (resp.data.code === 200) {
          showMessage('创建成功', 'success')
          router.push('/dashboard/tran')
        } else {
          showMessage('创建失败，原因：' + resp.data.msg, 'error');
        }
      })
    }
  })
}
</script>

<template>
  <el-form
      ref="clueRemarkRuleFormRef"
      :rules="customerRemarkRules"
      :model="customerRemark"
      label-width="121">

    <el-form-item label="ID">
      <div class="desc">&nbsp;{{customerDetail.id}}</div>
    </el-form-item>

    <el-form-item label="客户详情">
      <div class="desc">&nbsp;<router-link :to="'/dashboard/clue/detail/'+customerDetail.clueId">查看客户详情</router-link></div>
    </el-form-item>

    <el-form-item label="意向产品">
      <div class="desc">&nbsp;{{customerDetail.intentionProductDO.name}}</div>
    </el-form-item>

    <el-form-item label="客户描述">
      <div class="desc">&nbsp;{{customerDetail.description}}</div>
    </el-form-item>

    <el-form-item label="下次跟踪时间">
      <div class="desc">&nbsp;{{customerDetail.nextContactTime}}</div>
    </el-form-item>

    <el-form-item label="创建时间">
      <div class="desc">&nbsp;{{customerDetail.createTime}}</div>
    </el-form-item>

    <el-form-item label="创建人">
      <div class="desc">&nbsp;{{customerDetail.createByDO.name}}</div>
    </el-form-item>

    <el-form-item label="编辑时间">
      <div class="desc">&nbsp;{{customerDetail.editTime}}</div>
    </el-form-item>

    <el-form-item label="编辑人">
      <div class="desc">&nbsp;{{customerDetail.editByDO.name}}</div>
    </el-form-item>

    <el-form-item label="跟踪记录" prop="noteContent">
      <el-input
          v-model="customerRemark.noteContent"
          style="padding-left: 0;"
          :rows="8"
          type="textarea"
          maxlength="255"
          show-word-limit
          placeholder="请输入线索跟踪记录"/>
    </el-form-item>

    <el-form-item label="跟踪方式" prop="noteWay">
      <el-select
          v-model="customerRemark.noteWay"
          placeholder="请选择跟踪方式"
          style="width: 100%;padding-left: 0;"
          clearable
          @click="loadDicValue('noteWay')">
        <el-option v-for="item in noteWayOptions" :key="item.id" :label="item.typeValue" :value="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="success" @click="customerRemarkSubmit(clueRemarkRuleFormRef)">提 交</el-button>
      <el-button type="primary" @click="createTran">创建交易</el-button>
      <el-button type="success" plain @click="goBack">返 回</el-button>
    </el-form-item>

    <el-form-item label="历史跟踪记录">
      <el-table
          :data="customerRemarkList"
          style="width: 100%">
        <el-table-column type="index" label="序号" width="60"/>
        <el-table-column property="noteWayDO.typeValue" label="跟踪方式"/>
        <el-table-column property="noteContent" label="跟踪内容"/>
        <el-table-column property="createTime" label="创建时间"/>
        <el-table-column property="createByDO.name" label="创建人"/>
        <el-table-column property="editTime" label="编辑时间"/>
        <el-table-column property="editByDO.name" label="编辑人"/>
        <el-table-column label="操作" width="90">
          <template #default="scope">
            <a href="javascript:void(0)" style="margin-right: 8px;" @click="edit(scope.row.id)">编辑</a>
            <a href="javascript:void(0)" @click="del(scope.row.id)">删除</a>
          </template>
        </el-table-column>
      </el-table>
      <br/>
      <el-pagination :background="true"
                     layout="prev, pager, next, jumper, ->, total"
                     :total="total"
                     :page-size="pageSize"
                     @current-change="toPage"/>
    </el-form-item>
  </el-form>

  <!-- 创建交易的蒙版弹层对话框 -->
  <el-dialog v-model="createTranVisible" title="创建交易" width="800" center>
    <el-form ref="tranFormRef" :model="tranQuery" label-width="auto" :rules="tranRules">
      <el-form-item label="交易金额" prop="money">
        <el-input v-model="tranQuery.money"/>
      </el-form-item>

      <el-form-item label="预计成交时间" prop="expectedDate">
        <el-date-picker
            v-model="tranQuery.expectedDate"
            type="datetime"
            placeholder="请选择预计成交时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:100%;"/>
      </el-form-item>

      <el-form-item label="交易阶段" prop="stage">
        <el-select v-model="tranQuery.stage" placeholder="请选择交易阶段" @click="loadDicValue('stage')">
          <el-option
              v-for="item in stageOptions"
              :key="item.id"
              :label="item.typeValue"
              :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="交易描述" prop="description">
        <el-input
            v-model="tranQuery.description"
            :rows="8"
            type="textarea"
            maxlength="255"
            show-word-limit
            placeholder="请输入交易描述"/>
      </el-form-item>

      <el-form-item label="下次跟踪时间" prop="nextContactTime">
        <el-date-picker
            v-model="tranQuery.nextContactTime"
            type="datetime"
            placeholder="请选择下次跟踪时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width:100%;"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="createTranVisible = false">关 闭</el-button>
        <el-button type="primary" @click="createTranSubmit(tranFormRef)">创 建</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.desc {
  background: azure;
  width: 100%;
  margin-left: 10px;
  padding-left: 10px;
}
.el-table {
  margin-bottom: 15px;
}
</style>